
import { Application } from 'egg';
import { MEDIUMINT, TEXT, INTEGER, Instance } from 'sequelize';

export interface IDraftAttr {
  id?: number;
  authorId: number;
  articleId?: number;
  content: string;
  status?: number;
}

interface IDraftInst extends Instance<IDraftAttr>, IDraftAttr { }

export default (app: Application) => {
  const model = app.model.define<IDraftInst, IDraftAttr>('draft', {
    id: {
      type: MEDIUMINT(8).UNSIGNED,
      allowNull: false,
      autoIncrement: true,
      primaryKey: true,
    },
    authorId: {
      type: MEDIUMINT(8).UNSIGNED,
      allowNull: false,
    },
    articleId: {
      type: MEDIUMINT(8).UNSIGNED,
      allowNull: true,
    },
    content: {
      type: TEXT,
      allowNull: false,
    },
    status: {
      type: INTEGER(10),
      allowNull: false,
      defaultValue: 1,
    },
  }, {
    timestamps: true,
    paranoid: false,
    charset: 'utf8mb4',
    defaultScope: {
      where: {
        status: 1,
      },
    },
  });

  model.associate = () => {
    app.model.Draft.belongsTo(app.model.User, { as: 'author', foreignKey: 'authorId' });
    app.model.Draft.belongsTo(app.model.Article, { as: 'article', foreignKey: 'articleId' });
  };

  // model.sync({ alter: true });
  // model.sync({force: true}); //强制
  return model;
};
